using System;
using System.Collections.Generic;
using Jalal.Library.DataStructure;
using System.Data.SqlTypes;
using System.Data;
using Jalal.Library.Utility;
using Jalal.Library.Data;
using BCGC.DAL;
namespace BCGC.BLL.BusinessObject.Resource
{
    public class Wallpaper : ResourceBase
    {
        private int wallpaperId;
        public int WallpaperId
        {
            get { return wallpaperId; }
            private set { wallpaperId = value; }
        }

        private String thumbnailFileUrl;
        public String ThumbnailFileUrl
        {
            get
            {
                return thumbnailFileUrl;
            }
            set
            {
                thumbnailFileUrl = value;
            }
        }

        private ReadWriteCustomCollection<WallpaperSize> sizes;
        public ReadOnlyCustomCollection<WallpaperSize> Sizes
        {
            get { return sizes.ReadOnlyClone(); }
            private set { sizes = new ReadWriteCustomCollection<WallpaperSize>(value); }
        }


        public Wallpaper()
        {
            this.createDateTime = SqlDateTime.MinValue.Value;
            this.description = string.Empty;
            this.isActive = false;
            this.relatedGame = null;
            this.sizes = null;
            this.thumbnailFileUrl = string.Empty;
            this.title = string.Empty;
            this.wallpaperId = 0;
            this.totalView = 0;
            this.rating = 0;
            this.totalRatingVote = 0;
        }

        public Wallpaper(DataRow dataRow, bool fullLoad)
        {
            if (dataRow != null)
            {
                if (dataRow.Table.Columns.Contains("WallpaperId"))
                    this.wallpaperId = (int)CommonUtility.FilterNull(dataRow["WallpaperId"], typeof(int));
                if (dataRow.Table.Columns.Contains("ThumbnailFileUrl"))
                    this.thumbnailFileUrl = (string)CommonUtility.FilterNull(dataRow["ThumbnailFileUrl"], typeof(string));
                if (dataRow.Table.Columns.Contains("CreateDateTime"))
                    this.createDateTime = (DateTime)CommonUtility.FilterNull(dataRow["CreateDateTime"], typeof(DateTime));
                if (dataRow.Table.Columns.Contains("Description"))
                    this.description = (string)CommonUtility.FilterNull(dataRow["Description"], typeof(string));
                if (dataRow.Table.Columns.Contains("Title"))
                    this.title = (string)CommonUtility.FilterNull(dataRow["Title"], typeof(string));
                if (dataRow.Table.Columns.Contains("IsActive"))
                    this.isActive = (bool)CommonUtility.FilterNull(dataRow["IsActive"], typeof(bool));
                if (dataRow.Table.Columns.Contains("TotalView"))
                    this.totalView = (int)CommonUtility.FilterNull(dataRow["TotalView"], typeof(int));
                if (dataRow.Table.Columns.Contains("Rating"))
                    this.rating = (int)CommonUtility.FilterNull(dataRow["Rating"], typeof(int));
                if (dataRow.Table.Columns.Contains("TotalRatingVote"))
                    this.totalRatingVote = (int)CommonUtility.FilterNull(dataRow["TotalRatingVote"], typeof(int));

                if (fullLoad)
                {
                    this.relatedGame = new Game(dataRow);
                    this.sizes = WallpaperSize.GetAllWallpaperSizesByWallpaperId(wallpaperId);
                }
                else
                {
                    this.relatedGame = null;
                    this.sizes = null;
                }
            }
            else
            {
                this.createDateTime = SqlDateTime.MinValue.Value;
                this.description = string.Empty;
                this.isActive = false;
                this.relatedGame = null;
                this.sizes = null;
                this.thumbnailFileUrl = string.Empty;
                this.title = string.Empty;
                this.wallpaperId = 0;
                this.totalView = 0;
                this.rating = 0;
                this.totalRatingVote = 0;
            }
        }

        private static ReadWriteCustomCollection<Wallpaper> LoadFromDataTable(DataTable data)
        {
            ReadWriteCustomCollection<Wallpaper> result = new ReadWriteCustomCollection<Wallpaper>();

            if (data != null && data.Rows.Count > 0)
            {
                foreach (DataRow row in data.Rows)
                {
                    result.Add(new Wallpaper(row, true));
                }
            }
            return result;
        }

        public static void UpdateActive(List<int> activeWallpapers, List<int> inactiveWallpapers)
        {
            DataFactory.GetDataMiner().BeginTransaction(false);

            try
            {
                int updatedItemCount = ResourceData.UpdateActiveWallpaper(activeWallpapers,
                    inactiveWallpapers);
                if (updatedItemCount == activeWallpapers.Count + inactiveWallpapers.Count)
                    DataFactory.GetDataMiner().CommitTransaction();
                else
                    throw new Exception("Failed to update all items");
            }
            catch (Exception ex)
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                throw ex;
            }
        }

        public static void Delete(List<int> wallpapersToDelete)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            DataTable wallpaperFiles = ResourceData.GetWallpaperFileLocationsForDelete(wallpapersToDelete);
            DataTable wallpaperSizeFiles = ResourceData.GetWallpaperSizeFileLocationsForDeleteByWallpaperId(wallpapersToDelete);
            DataFactory.GetDataMiner().CommitTransaction();

            DataFactory.GetDataMiner().BeginTransaction(false);

            try
            {
                int deletedItemCount = ResourceData.DeleteWallpapers(wallpapersToDelete);
                if (deletedItemCount == wallpapersToDelete.Count)
                    DataFactory.GetDataMiner().CommitTransaction();
                else
                    throw new Exception("Failed to delete all items");

                if (wallpaperFiles != null && wallpaperFiles.Rows.Count > 0)
                {
                    foreach (DataRow row in wallpaperFiles.Rows)
                    {
                        string thumbnailFileUrl = Convert.ToString(row["ThumbnailFileUrl"]);
                        if (!string.IsNullOrEmpty(thumbnailFileUrl))
                            FileAccessUtility.DeleteFile(thumbnailFileUrl);
                    }
                }

                if (wallpaperSizeFiles != null && wallpaperSizeFiles.Rows.Count > 0)
                {
                    foreach (DataRow row in wallpaperSizeFiles.Rows)
                    {
                        string sizeFileUrl = Convert.ToString(row["SizeFileUrl"]);
                        if (!string.IsNullOrEmpty(sizeFileUrl))
                            FileAccessUtility.DeleteFile(sizeFileUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                throw ex;
            }
        }

        public static ReadWriteCustomCollection<Wallpaper> GetAllWallpapers(int currentPageIndex, 
            string sortOrder, int pageSize, string searchTitle, string searchGameTitle, 
            DateTime? createDateFrom, DateTime? createDateTo, bool? isActive, out int totalData)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);

            totalData = 0;

            DataTable wallpaperData = ResourceData.GetAllWallpapers(currentPageIndex, sortOrder, pageSize,
                searchTitle, searchGameTitle, createDateFrom, createDateTo, isActive, out totalData);
            ReadWriteCustomCollection<Wallpaper> wallpapers = LoadFromDataTable(wallpaperData);

            DataFactory.GetDataMiner().CommitTransaction();

            return wallpapers;
        }

        public static bool Create(string title, int gameId, string description, 
            string thumbImageUrl, string defaultSizeName, string defaultSizeUrl, bool isActive)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            int id = ResourceData.CreateNewWallpaper(title, gameId, description, 
                thumbImageUrl, defaultSizeName, defaultSizeUrl, isActive);
            DataFactory.GetDataMiner().CommitTransaction();

            return (id > 0);
        }

        public static Wallpaper GetWallpaperById(int id)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            Wallpaper wallpaper = null;
            DataTable data = ResourceData.GetWallpaperById(id);
            if (data != null && data.Rows.Count > 0)
                wallpaper = new Wallpaper(data.Rows[0], true);

            DataFactory.GetDataMiner().CommitTransaction();

            return wallpaper;
        }

        public static bool Update(int wallpaperId, string title, int gameId, string description,
            string thumbImageUrl, string defaultSizeName, string defaultSizeUrl, bool isActive)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            List<int> wallpapersToDelete = new List<int>();
            wallpapersToDelete.Add(wallpaperId);
            DataTable wallpaperFiles = ResourceData.GetWallpaperFileLocationsForDelete(wallpapersToDelete);
            DataFactory.GetDataMiner().CommitTransaction();

            if (wallpaperFiles != null && wallpaperFiles.Rows.Count > 0)
            {
                foreach (DataRow row in wallpaperFiles.Rows)
                {
                    string thumbnailFileUrl = Convert.ToString(row["ThumbnailFileUrl"]);
                    if (!string.IsNullOrEmpty(thumbnailFileUrl))
                        FileAccessUtility.DeleteFile(thumbnailFileUrl);

                    string bigFileUrl = Convert.ToString(row["SizeFileUrl"]);
                    if (!string.IsNullOrEmpty(bigFileUrl))
                        FileAccessUtility.DeleteFile(bigFileUrl);
                }
            }

            DataFactory.GetDataMiner().BeginTransaction(true);
            int updateCount = ResourceData.UpdateWallpaper(wallpaperId, title, gameId, description, thumbImageUrl,
                defaultSizeName, defaultSizeUrl,isActive);
            DataFactory.GetDataMiner().CommitTransaction();

            return (updateCount > 0);
        }

        public static ReadWriteCustomCollection<Wallpaper> GetAllWallpapersByGame(int currentPageIndex, string sortOrder, 
            int pageSize, int gameId, out int totalData)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);

            totalData = 0;

            DataTable wallpaperData = ResourceData.GetAllWallpapersByGameId(currentPageIndex, sortOrder, pageSize,
                gameId, out totalData);
            ReadWriteCustomCollection<Wallpaper> wallpapers = LoadFromDataTable(wallpaperData);

            DataFactory.GetDataMiner().CommitTransaction();

            return wallpapers;
        }
    }

}
